package com.chzc.goods.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chzc.goods.mapper.GoodsMapper;
import com.chzc.goods.service.IGoodsCarService;
import com.chzc.po.Goods;
import com.chzc.util.Result;
import com.chzc.util.json.JsonUtil;
import com.chzc.vo.CarVo;
import com.chzc.vo.GoodsItemCarVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author cv大魔王
 * @version 1.0
 * @date 2021/6/6 16:43
 */
@Service
public class GoodsCarServiceImpl implements IGoodsCarService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Result add(String goodsId, int buyNum) {
        // 获取购物车
        BoundHashOperations<String, Object, Object> myCart = getMyCartOps();
        Object cacheObj = myCart.get(goodsId);
        String result = "";
        if (cacheObj != null) {
            result = (String) cacheObj;
        }

        // 购物车没这个商品
        if (cacheObj == null) {
            // 获取商品信息
            GoodsItemCarVO goodsItemCarVO = getGoodsDetail(goodsId, buyNum);
            // 商品信息存入到Redis
            myCart.put(goodsId, Objects.requireNonNull(JsonUtil.objectToJson(goodsItemCarVO)));
            // 老的商品数量加新的商品数量
            if (buyNum <= 0) {
                // 删除商品
                Long delete = myCart.delete(goodsId);
            }
        } else {
            // 商品购买数量
            GoodsItemCarVO goodsItemCarVO = JsonUtil.jsonToPojo(result, GoodsItemCarVO.class);
            // 老的商品数量加新的商品数量
            if (buyNum + goodsItemCarVO.getBuyNum() <= 0) {
                // 删除商品
                Long delete = myCart.delete(goodsId);
            }else {
                goodsItemCarVO.setBuyNum(buyNum + goodsItemCarVO.getBuyNum());
                myCart.put(goodsId, Objects.requireNonNull(JsonUtil.objectToJson(goodsItemCarVO)));
            }
        }
        return findAll();
    }

    @Override
    public Result findAll() {
        BoundHashOperations<String, Object, Object> myCart = getMyCartOps();
        List<Object> itemList = myCart.values();
        List<GoodsItemCarVO> goodsItemCarVOS = new ArrayList<>();

        for (Object item : itemList) {
            GoodsItemCarVO cartItemVO = JsonUtil.jsonToPojo((String) item, GoodsItemCarVO.class);
            goodsItemCarVOS.add(cartItemVO);
        }
        //封装成cartvo
        CarVo cartVO = new CarVo();
        cartVO.setCartItems(goodsItemCarVOS);
        return Result.querySuccess(cartVO);
    }

    @Override
    public Result deleteByGoodsId(String goodsId) {
        // 获取购物车
        BoundHashOperations<String, Object, Object> myCart = getMyCartOps();
        myCart.delete(goodsId);
        return findAll();
    }

    @Override
    public Result deleteAll() {
        redisTemplate.delete(getCartKey());
        return Result.deleteSuccess();
    }

    /**
     * 获取商品信息
     *
     * @param goodsId 商品ID
     * @param buyNum  商品数量
     * @return 商品详细信息
     */
    private GoodsItemCarVO getGoodsDetail(String goodsId, Integer buyNum) {
        Goods goods = findGoodsById(goodsId);
        GoodsItemCarVO carVO = new GoodsItemCarVO();
        carVO.setId(goods.getId());
        carVO.setGoodsTitle(goods.getGoodsTitle());
        carVO.setGoodsImg(goods.getGoodsImg());
        carVO.setGoodsContent(goods.getGoodsContent());
        carVO.setGoodsPrice(goods.getGoodsPrice());
        carVO.setSeckillPrice(goods.getSeckillPrice());
        carVO.setStartDate(goods.getStartDate());
        carVO.setEndDate(goods.getEndDate());
        carVO.setBuyNum(buyNum);
        return carVO;
    }


    @Cacheable(value = {"goods"}, key = "#root.methodName+'_'+#root.method+'_'+#goodsId")
    public Goods findGoodsById(String goodsId) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("id", goodsId);
        wrapper.select("id", "goods_title", "goods_img", "goods_price", "goods_content", "seckill_price", "start_date", "end_date");
        return goodsMapper.selectOne(wrapper);
    }

    /**
     * 抽取我的购物车通用方法
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getMyCartOps() {
        String key = getCartKey();
        return redisTemplate.boundHashOps(key);
    }


    /**
     * 获取购物车的Key
     *
     * @return 购物车的key
     */
    private String getCartKey() {
        // 当前登录的用户id
        String userId = StpUtil.getLoginIdAsString();
        String cartKey = String.format("goods::cart:%s", userId);
        return cartKey;
    }


}
